<template>
  <div class="eig-column">
    <div class="eig-filter">
      <div class="filter-right">
        <a-space>
          <a-input-search
            v-model:value="searchValue"
            placeholder="input search text"
            style="width: 200px"
            @search="onSearch"
          />
          <a-button class="eig-icon-btn" @click="onRefresh">
            <template #icon>
              <RedoOutlined :style="{ color: 'rgba(0, 0, 0, 0.45)' }" />
            </template>
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="eig-table">
      <a-table
        :columns="columns"
        :data-source="recordList"
        :scroll="{ y: 'calc(100vh - 220px' }"
      >
        <template #bodyCell="{ column, text, record }">
          <template
            v-if="
              column.dataIndex === 'reportName' ||
              column.dataIndex === 'describe'
            "
          >
            <div class="editable-cell">
              <div
                v-if="editableData[`${record.id}_${column.dataIndex}`]"
                class="editable-cell-input-wrapper"
              >
                <a-input
                  v-if="column.dataIndex === 'reportName'"
                  v-model:value="
                    editableData[`${record.id}_${column.dataIndex}`].reportName
                  "
                  ref="input_name"
                  style="width: 120px"
                  size="small"
                  @pressEnter="save(record.id, column.dataIndex)"
                  @blur="save(record.id, column.dataIndex)"
                />

                <a-input
                  v-if="column.dataIndex === 'describe'"
                  v-model:value="
                    editableData[`${record.id}_${column.dataIndex}`].describe
                  "
                  size="small"
                  ref="input_describe"
                  @pressEnter="save(record.id, column.dataIndex)"
                  @blur="save(record.id, column.dataIndex)"
                />
              </div>
              <div v-else class="editable-cell-text-wrapper">
                <p>
                  <a
                    v-if="column.dataIndex === 'reportName'"
                    Href="javascript:;"
                    @click="lookRecord(record.id)"
                    >{{ text || " " }}</a
                  >
                  <span v-else>
                    {{ text || " " }}
                  </span>
                  <edit-outlined
                    class="editable-cell-icon"
                    @click="edit(record.id, column.dataIndex)"
                  />
                </p>
                <p v-if="column.dataIndex === 'reportName'">
                  <span>{{ record.instanceID }}</span>
                </p>
              </div>
            </div>
          </template>
          <template v-if="column.dataIndex === 'name'">
            <span>{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'gender'">
            <span>{{
              record.gender === 1 ? "男" : record.gender === 2 ? "女" : "未知"
            }}</span>
          </template>
          <template v-if="column.dataIndex === 'recoredCreateTime'">
            <span>{{
              formatTimestamp(text, "yyyy-MM-dd HH:mm:ss", true)
            }}</span>
          </template>
          <template v-if="column.dataIndex === 'recoredTotalTime'">
            <span>{{ tipFormatter(text) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a @click="deleteRow(record)">删除</a>
            <a-divider type="vertical" />
            <a @click="$exportCsv(record, 'reportSource')">导出数据</a>
            <a-divider type="vertical" />
            <a @click="exportRecord(record)">导出报告</a>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  nextTick,
  getCurrentInstance,
} from "vue";
import type { Ref, UnwrapRef } from "vue";
import { useRoute, useRouter } from "vue-router";
import { RedoOutlined } from "@ant-design/icons-vue";
import { formatTimestamp, tipFormatter } from "../../../utils/common";
const searchValue = ref<string>("");
import { cloneDeep } from "lodash-es";
import { CheckOutlined, EditOutlined } from "@ant-design/icons-vue";
import { CustomDatabase } from "../../../utils/db";
import { Modal } from "ant-design-vue";
import { storeToRefs } from "pinia";
import { useIndexStore } from "../../../store/index";
import { message } from "ant-design-vue";
import { DataItem } from "../../../types";
const app = getCurrentInstance();
const router = useRouter();
const ipcRenderer = require("electron").ipcRenderer;
const indexStore = useIndexStore();
const { play, recordId, configData } = storeToRefs(indexStore);
const input_name = ref();
const input_describe = ref();
const db = new CustomDatabase();
let currentRecord: DataItem | null;

const recordList = ref<DataItem[]>([]);

const columns = [
  {
    title: "名称/ID",
    dataIndex: "reportName",
  },
  {
    title: "创建时间",
    dataIndex: "recoredCreateTime",
  },
  {
    title: "姓名",
    dataIndex: "name",
  },
  {
    title: "年龄",
    dataIndex: "age",
  },
  {
    title: "性别",
    dataIndex: "gender",
  },
  {
    title: "操作",
    dataIndex: "operation",
  },
];

onMounted(() => {
  ipcRenderer.on("pdf-read-response", pdfReadResponse);
  getDate();
});

const exportRecord = (record: DataItem) => {
  app?.proxy?.loading.show("导出中...");
  currentRecord = record;
  ipcRenderer.send("pdf-read", record.instanceID);
};

const getDate = async () => {
  let list = await db.all(
    `select id,instanceID,reportName,name,age,gender,recoredCreateTime,recoredTotalTime,recoredEndTime,describe,waveLength,eegInputMarkerList,irInputMarkerList,markerList,configText from reportRecord where  '${searchValue.value}' = '' or name Like '%${searchValue.value}%'  or instanceID Like '%${searchValue.value}%'`
  );
  recordList.value = list.sort(
    (a, b) => b.recoredCreateTime - a.recoredCreateTime
  );
};

const onRefresh = async () => {
  await getDate();
  message.success("已刷新！");
};

const deleteRow = (record: DataItem) => {
  Modal.confirm({
    title: "确认删除数据？",
    content: `确认要删除数据：${record.name}吗？`,
    okText: "确认",
    cancelText: "取消",
    onOk() {
      app?.proxy?.loading.show("删除中...");
      db.delete("reportRecord", { id: record.id })
        .then(() => {
          recordList.value = recordList.value.filter(
            (item) => item.id !== record.id
          );
          app?.proxy?.loading.hide();
          ipcRenderer.send("pdf-delete", record.instanceID);
          db.delete("reportSource", { recordId: record.id });
        })
        .catch(() => {
          message.error("删除reportRecord失败");
        });
    },
  });
};

const onSearch = (searchValue: string) => {
  getDate();
};

const pdfReadResponse = (event, resp) => {
  if (resp.code == 201) {
    const url = URL.createObjectURL(
      new Blob([resp.data, { type: "application/pdf" }])
    );

    // Prompt the user to save the file
    const a = document.createElement("a");
    a.href = url;
    a.download = `${currentRecord?.reportName}.pdf`; // Set the file name
    a.click();

    // Clean up
    URL.revokeObjectURL(url);
  } else {
    message.error("文件不存在！");
  }
  app?.proxy?.loading.hide();
};

const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

const edit = (id: number, dataIndex) => {
  editableData[`${id}_${dataIndex}`] = cloneDeep(
    recordList.value.filter((item) => id === item.id)[0]
  );
  nextTick(() => {
    if (dataIndex === "reportName") {
      input_name.value.focus();
    }
    if (dataIndex === "describe") {
      input_describe.value.focus();
    }
  });
};
const save = (id: number, dataIndex) => {
  Object.assign(
    recordList.value.filter((item) => id === item.id)[0],
    editableData[`${id}_${dataIndex}`]
  );
  db.update("reportRecord", editableData[`${id}_${dataIndex}`], { id }).then(
    () => {
      message.success("修改成功");
      delete editableData[`${id}_${dataIndex}`];
    }
  );
};

const lookRecord = (id) => {
  debugger;
  indexStore.playIndex = 0;
  indexStore.recordId = id;
  indexStore.recordType = "report";
  router.push("/EEG");
};

onBeforeUnmount(() => {
  ipcRenderer.removeListener("pdf-read-response", pdfReadResponse);
});
</script>

<style scoped></style>
